package com.jse.util.concurrent.new1.collection;

import org.junit.Test;

import java.util.List;
import java.util.concurrent.CopyOnWriteArrayList;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * @author : zenghua
 * @version : v0.1 CopyOnWriteArrayListTest.java
 * @since : 2018/3/28 11:34
 */
public class CopyOnWriteArrayListTest {

	@Test
	public void testAdd() throws Exception {
		CopyOnWriteArrayList<Integer> list = new CopyOnWriteArrayList<>();
		ExecutorService executorService = Executors.newFixedThreadPool(10);
		CountDownLatch latch = new CountDownLatch(100);

		for (int i = 0; i < 100; i++) {
			executorService.execute(new WriteTask(i, list, latch));
		}
		latch.await();
		System.out.println(list.size());
		for (Integer e : list) {
			System.out.println(e);
		}
	}

	class WriteTask implements Runnable {
		private int i;
		private List<Integer> dataList;
		private CountDownLatch latch;

		public WriteTask(int i, List<Integer> dataList, CountDownLatch latch) {
			this.i = i;
			this.dataList = dataList;
			this.latch = latch;
		}

		@Override
		public void run() {
			dataList.add(i);
			latch.countDown();
		}
	}
}
